﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using WebService.Models;

namespace WebService.Filter
{
    /// <summary>
    /// 统一接口返回过滤器
    /// </summary>
    public class UnifyAPIResultFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //特殊处理：对有ApiIgnoreAttribute标签的，不进行返回结果包装，原样输出
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                var isDefined = controllerActionDescriptor
                    .EndpointMetadata.Any(a => a.GetType().Equals(typeof(NonUnifyAPIAttribute)));
                if (isDefined)
                {
                    return;
                }

            }
            // 返回结果为JsonResult的请求进行Result包装
            if (context.Result != null)
            {
                var model = new ProcessResult();
                if (context.Result is ObjectResult objectResult)
                {
                    if (objectResult.Value is ProcessResult ret)
                    {
                        context.Result = new JsonResult(ret);
                    }
                    else
                    {
                        model.SetSuccess(objectResult.Value);
                        context.Result = new JsonResult(model);
                    }
                }
                else if (context.Result is EmptyResult)
                {
                    model.SetSuccess();
                    context.Result = new JsonResult(model);
                }
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            
        }
    }

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public sealed class NonUnifyAPIAttribute : Attribute
    {
    }
}
